package com.vfa.fishing;


import java.util.ArrayList;
import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.FixedStepEngine;
import org.anddev.andengine.engine.camera.BoundCamera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperties;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTile;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileProperty;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader.ITMXTilePropertiesListener;
import org.anddev.andengine.entity.layer.tiled.tmx.util.exception.TMXLoadException;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;
import com.vfa.fishing.animal.Crab;
import com.vfa.fishing.animal.Fish;
import com.vfa.fishing.animal.Moss;
import com.vfa.fishing.animal.Person;
import com.vfa.fishing.animal.Shells;
import com.vfa.fishing.animal.Shrimp;
import com.vfa.fishing.common.AbstractObject;
import com.vfa.fishing.common.Constant;
import com.vfa.fishing.common.Utils;
import com.vfa.fishing.data.AnimalModel;
import com.vfa.fishing.data.AnimalToRestore;
import com.vfa.fishing.data.GameModel;
import com.vfa.fishing.data.MainGame;
import com.vfa.fishing.data.PersonModel;
import com.vfa.fishing.data.PersonToRestore;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;


public class GameActivity extends BaseGameActivity implements IOnSceneTouchListener, IOnAreaTouchListener {
    // ===========================================================
    // Constants
    // ===========================================================

    //private static final int LAYER_BACKGROUND = 0;
    //private static final int LAYER_FOOD = LAYER_BACKGROUND + 1;
    //private static final int LAYER_SNAKE = LAYER_FOOD + 1;

    private final int stepsPerSecond = 100; // chinh do smooth cua game
    public static int TIMER = 0;

    private static final int WIDTH_OF_TIMER_BAR = 200;
    private static final int HEIGHT_OF_TIMER_BAR = 20;
    // ===========================================================
    // Fields
    // ===========================================================

    private BoundCamera mBoundCamera;
    private TMXTiledMap mTMXTiledMap;

    private Texture mFontTexture;
    private Texture mBoatTexture;
    private Texture mMossTexture;
    private Texture mCrabTexture;
    private Texture mShellsTexture;
    private Texture mfishingrodTexture;
    private Texture mfishingIconTexture;
    private Texture arrTextureFish [];
    private Texture arrTextureShrimp [];
    private TiledTextureRegion arrFishImg [];
    private TiledTextureRegion arrFishImgBack [];
    private TiledTextureRegion arrShrimpImg [];
    private TiledTextureRegion arrShrimpImgBack [];
    private TiledTextureRegion boatTextureRegion;
    private TiledTextureRegion mossTextureRegion;
    private TiledTextureRegion crabTextureRegion;
    private TiledTextureRegion shellsTextureRegion;
    private TiledTextureRegion mfishingrodTextureRegion;
    private TiledTextureRegion mfishingIconTextureRegion;
    //private Scene myScene;
    private Scene myScene = new Scene(2);
    private AnimatedSprite iconcau;
    private AnimatedSprite hook;
    private ChangeableText mGameOverText;
    private ChangeableText mCongratulationsText;
    private ChangeableText mScoreText;
    private ChangeableText mFishText;
    private ChangeableText mLevelText;
    private ChangeableText mGoalText;
    private Shape cheat;
    private TMXLoader tmxLoader;
    
    // danh sach chua tat ca cac doi tuong trong game, dung danh sach nay de check va cham voi cac doi tuong khac
    public ArrayList<AbstractObject > arrAllObject ;
    private Person boat;
    private Line line; // day cau
    private Fish fishColie = null;
    private Shrimp shrimpColie = null;
    private Crab crabColie = null;
    private Shells shellsColie = null;

    private AnimalModel animalModel;
    private PersonModel personModel;
    private GameModel gameModel;

    private PauseMenuDialog pauseMenu;
    private NextLevelDialog nextLevel;
    private EndGameDialog endGame;
    private Rectangle timerBar;
    private HUD myHud;
    private Font mFont;

    public static Random rand;
    private SharedPreferences settings;

    private int Xtarget;
    private int iTimeToResetDirect;
    private int lengthInTime = Constant.DISTANCELINE;// do dai tang len/giam di sau 1 luot update
    private int sideAppear;
    private int indexFish;
    private int indexShrimp;
    private int indexCrab;
    private int indexShells;
    private int iXIconcau;
    private int iYIconcau;
    private int percentTimeBar;
    private int nLevel;
    private int isOverGameorCongras = 0;
    public static int iTimerInLevel;


    private boolean isLoadGame;
    private boolean isSaveGame;
    public static boolean isIncreaseLevel;
    private boolean isReset = false;
    private boolean isPickUp = false;//dang tha day cau xuong
    protected boolean mGameRunning = true;
    private int  iTotalScore;
    public static boolean isTryAgain = false;

//    private SoundPool sounds;
//    private HashMap <Integer, Integer> soundPoolMap;
    private MediaPlayer bgSound;
    private MediaPlayer fishbeatSound;
    private int [] arrayBgSound={R.raw.fishbg1,R.raw.fishbg2,R.raw.tidebg1,R.raw.tidebg2};
    private int indexBgSound = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        isLoadGame = false;

    }

    @Override
    public Engine onLoadEngine() {
        this.mBoundCamera = new BoundCamera(0, 0, 800, 480);
//        return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(MenuActivity.CAMERA_WIDTH, MenuActivity.CAMERA_HEIGHT), this.mBoundCamera).setNeedsSound(true));
        return new FixedStepEngine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(MenuActivity.CAMERA_WIDTH, MenuActivity.CAMERA_HEIGHT), this.mBoundCamera).setNeedsSound(true), stepsPerSecond);
    }

    @Override
    public void onLoadResources() {

        arrAllObject  = new ArrayList<AbstractObject>();
        rand = new Random();
        rand.setSeed(System.currentTimeMillis());
        Xtarget = 400;
        iXIconcau = 700;
        iYIconcau = 400;
        nLevel = 1;
        percentTimeBar = 100;
        iTimerInLevel = Constant.arrayTimeInLevels[nLevel-1];
        iTotalScore = 0;
        arrTextureFish = new Texture[Constant.NUM_OF_KIND_FISH];
        arrTextureShrimp = new Texture[Constant.NUM_OF_KIND_SHRIMP];

        arrFishImg = new TiledTextureRegion[Constant.NUM_OF_KIND_FISH];
        arrFishImgBack = new TiledTextureRegion[Constant.NUM_OF_KIND_FISH];
        arrShrimpImg = new TiledTextureRegion[Constant.NUM_OF_KIND_SHRIMP];
        arrShrimpImgBack = new TiledTextureRegion[Constant.NUM_OF_KIND_SHRIMP];

        /* Load the font we are going to use. */
        FontFactory.setAssetBasePath("font/");
        this.mFontTexture = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 20, true, Color.WHITE);
        this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
        this.mEngine.getFontManager().loadFont(this.mFont);

        TextureRegionFactory.setAssetBasePath("gfx/");

        this.mBoatTexture = new Texture(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.boatTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mBoatTexture, this, "boat.png", 0, 0, 1, 1);
        this.mfishingIconTexture = new Texture(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.mfishingIconTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mfishingIconTexture, this, "iconcau.png", 0, 0, 1, 1);
        this.mfishingrodTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.mfishingrodTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mfishingrodTexture, this, "luoicau.png", 0, 0, 1, 1);
        this.mMossTexture = new Texture(1024, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.mossTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mMossTexture, this, "moss.png", 0, 0, 4, 1);
        this.mCrabTexture = new Texture(512, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.crabTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mCrabTexture, this, "crab.png", 0, 0, 4, 1);
        this.mShellsTexture = new Texture(512, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.shellsTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mShellsTexture, this, "shell.png", 0, 0, 4, 1);


        for (int i = 0; i < Constant.NUM_OF_KIND_FISH; i++) {
            arrTextureFish[i] = new Texture(512, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            if (i == 4) {
                arrFishImg[i] = TextureRegionFactory.createTiledFromAsset(arrTextureFish[i], this, "fish" + i + ".png", 0, 0, 5, 1);
                arrFishImgBack[i] = TextureRegionFactory.createTiledFromAsset(arrTextureFish[i], this, "fish" + i + ".png", 0, 0, 5, 1);
            } else if (i == 5) {
                arrFishImg[i] = TextureRegionFactory.createTiledFromAsset(arrTextureFish[i], this, "fish" + i + ".png", 0, 0, 6, 1);
                arrFishImgBack[i] = TextureRegionFactory.createTiledFromAsset(arrTextureFish[i], this, "fish" + i + ".png", 0, 0, 6, 1);
            } else {
                arrFishImg[i] = TextureRegionFactory.createTiledFromAsset(arrTextureFish[i], this, "fish" + i + ".png", 0, 0, 4, 1);
                arrFishImgBack[i] = TextureRegionFactory.createTiledFromAsset(arrTextureFish[i], this, "fish" + i + ".png", 0, 0, 4, 1);
            }
            arrFishImgBack[i].setFlippedHorizontal(true);

        }

        for (int i = 0; i < Constant.NUM_OF_KIND_SHRIMP; i++) {
            arrTextureShrimp[i] = new Texture(1024, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            arrShrimpImg[i] = TextureRegionFactory.createTiledFromAsset(arrTextureShrimp[i], this, "shrimp" + ".png", 0, 0, 5, 1);
            arrShrimpImgBack[i] = TextureRegionFactory.createTiledFromAsset(arrTextureShrimp[i], this, "shrimp" + ".png", 0, 0, 5, 1);
        }

        this.mEngine.getTextureManager().loadTextures(mBoatTexture);
        this.mEngine.getTextureManager().loadTextures(arrTextureFish);
        this.mEngine.getTextureManager().loadTextures(arrTextureShrimp);
        this.mEngine.getTextureManager().loadTextures(mMossTexture);
        this.mEngine.getTextureManager().loadTextures(mCrabTexture);
        this.mEngine.getTextureManager().loadTextures(mShellsTexture);
        this.mEngine.getTextureManager().loadTextures(mfishingrodTexture);
        this.mEngine.getTextureManager().loadTextures(mfishingIconTexture);
        //init sound 
        bgSound = Utils.loadResInMediaPlayer(this, arrayBgSound[indexBgSound], bgSound);
        fishbeatSound = Utils.loadResInMediaPlayer(this, R.raw.firechange, fishbeatSound);

    }

    @Override
    public Scene onLoadScene() {

        this.mEngine.registerUpdateHandler(new FPSLogger());

        try {
                tmxLoader = new TMXLoader(this, this.mEngine.getTextureManager(), TextureOptions.BILINEAR_PREMULTIPLYALPHA, new ITMXTilePropertiesListener() {
                @Override
                public void onTMXTileWithPropertiesCreated(final TMXTiledMap pTMXTiledMap, final TMXLayer pTMXLayer, final TMXTile pTMXTile, final TMXProperties<TMXTileProperty> pTMXTileProperties) {
                }
            });
            this.mTMXTiledMap = tmxLoader.loadFromAsset(this, "tmx/bg1.tmx");

        } catch (final TMXLoadException tmxle) {
            Debug.e(tmxle);
        }

        final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
        myScene.getFirstChild().attachChild(tmxLayer);

        this.mBoundCamera.setBounds(0, tmxLayer.getWidth(), 0, tmxLayer.getHeight());
        this.mBoundCamera.setBoundsEnabled(true);

        myScene.registerUpdateHandler(new IUpdateHandler() {
            @Override
            public void reset() { }

            @Override
            public void onUpdate(final float pSecondsElapsed) { }
        });/* end map*/

        iconcau = new AnimatedSprite(iXIconcau, iYIconcau, this.mfishingIconTextureRegion);

        settings = getSharedPreferences(MenuActivity.PREFS_NAME, 0);
        isLoadGame = settings.getBoolean("loadGamemode", false);
        cheat = new Rectangle(0, 0, 100, 30);
        if(myHud == null) {
            myHud = new HUD(); // instance 1 hud
        }
        myHud.getLastChild().attachChild(iconcau); // add icon cau vao hud
        myHud.registerTouchArea(iconcau);
        myHud.registerTouchArea(cheat);
        myHud.setTouchAreaBindingEnabled(true);
        myHud.setOnAreaTouchListener(this); // dang ky su kien touch area
        mBoundCamera.setHUD(myHud); // set hud vao camera

     // show timer bar: begin
        Rectangle borderTimerBar = new Rectangle(10, 10, WIDTH_OF_TIMER_BAR + 4, HEIGHT_OF_TIMER_BAR + 4);
        borderTimerBar.setColor(1, 0.4f, 0.6f);
        timerBar = new Rectangle(12, 12, getWidthOfTimerBar(), HEIGHT_OF_TIMER_BAR);
        timerBar.setColor(.0f, .23f, .96f);
        myHud.getLastChild().attachChild(borderTimerBar);
        myHud.getLastChild().attachChild(timerBar);
        initGameText();

        if(isLoadGame){
            loadGame();//load tu database
        } else if(!isLoadGame){
            initilize(nLevel);// load du lieu cua cac doi tuong se duoc hien thi trong game len
        }

        myScene.setOnSceneTouchListener(this);
        /* di chuyen map theo boat */
        this.mBoundCamera.setChaseEntity(boat);

        /* Make the Snake move every 0.1 seconds. */
        TimerHandler timer = new TimerHandler(0.1f, true, new ITimerCallback() {
            @Override
            public void onTimePassed(final TimerHandler pTimerHandler) {

                TIMER++;

                if(TIMER > 1000000) {
                    TIMER = 0;
                }

                timerBar.setSize(getWidthOfTimerBar(), HEIGHT_OF_TIMER_BAR);
                updateBarTimer();
                update();                
            }
        });
        myScene.registerUpdateHandler(timer);
        myHud.registerUpdateHandler(timer);
        return myScene;
    }

    @Override
    public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent)
    {
        Xtarget = (int)pSceneTouchEvent.getX();
        if (lengthInTime > Constant.DISTANCELINE || !this.mGameRunning) {
            return false;
        }
        if (pSceneTouchEvent.isActionDown()) {
            return true;
        }
        if (pSceneTouchEvent.isActionMove()) {
            if (lengthInTime == Constant.DISTANCELINE)
            {
                boat.isMoving = true;
                boat.isFishing = false;
            }
            return true;
        }
        return false;
    }

    @Override
    public void onLoadComplete() {

    }

    public void update() {

        if (this.mGameRunning) {
            // check va cham
            checkColitionAllObject();
            checkBoundOfObject();

            // update nguoi cau ca
            if (boat != null && boat.isMoving && !boat.isFishing) {
                boat.update(Xtarget);
                moveLineFish();
            }

            // update day cau
            if (boat.isFishing)
            {
                paintLineFishing();
            }

            // update cac animal neu khong va cham
            for (int i = 0; i < arrAllObject.size(); i++) {
                if (!arrAllObject.get(i).checkCollision()) {
                    arrAllObject.get(i).update();
                }
            }
            
            //play sound
            if(!bgSound.isPlaying())
            {
            	if(indexBgSound < arrayBgSound.length-1) {
            		indexBgSound++;
            	} else {
            		indexBgSound = 0;
            	}
            	bgSound = Utils.loadResInMediaPlayer(GameActivity.this, arrayBgSound[indexBgSound], bgSound);
            	Utils.playMediaPlayer(bgSound, false);
            }
        }
    }

    private void checkBoundOfObject() {
        for (int i = 0; i < arrAllObject.size(); i++) {
            if (arrAllObject.get(i).checkCollision()) {
                myScene.getLastChild().detachChild(arrAllObject.get(i));
                if (arrAllObject.get(i).kindOfObject == Constant.MOSS) {
                    int y = rand.nextInt(100) + 160;
                    int x = -1;
                    int mossKind = rand.nextInt(2);
                    sideAppear = rand.nextInt(2);
                    if (sideAppear == Constant.LEFTSIDE) {
                        x = -20;
                    }
                    else if (sideAppear == Constant.RIGHTSIDE) {
                       x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                    }
                    Moss moss = new Moss(x, y, mossTextureRegion, sideAppear, mossKind);
                    moss.animate(1000);
                    arrAllObject.remove(i);
                    arrAllObject.add(i,(AbstractObject)moss);
                    myScene.getLastChild().attachChild(moss);
                    break;
                 }
                 else if (arrAllObject.get(i).kindOfObject == Constant.CRAB) {

                    int y = 420;
                    int x = -1;
                    int crabKind = 0;
                    sideAppear = rand.nextInt(2);
                    if (sideAppear == Constant.LEFTSIDE) {
                        x = -20;
                    }
                    else if (sideAppear == Constant.RIGHTSIDE) {
                       x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                    }
                    Crab crab = new Crab(x, y, crabTextureRegion, sideAppear, crabKind);
                    crab.animate(1000);
                    arrAllObject.remove(i);
                    arrAllObject.add(i,(AbstractObject)crab);
                    myScene.getLastChild().attachChild(crab);
                    break;
                 }
                 else if (arrAllObject.get(i).kindOfObject == Constant.SHELLS) {

                     int y = 450;
                     int x = -1;
                     int shellsKind = 0;
                     sideAppear = rand.nextInt(2);
                     if (sideAppear == Constant.LEFTSIDE) {
                         x = -30;
                     }
                     else if (sideAppear == Constant.RIGHTSIDE) {
                        x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 30;
                     }
                     Shells shells = new Shells(x, y, shellsTextureRegion, sideAppear, shellsKind);
                     shells.animate(200);
                     arrAllObject.remove(i);
                     arrAllObject.add(i,(AbstractObject)shells);
                     myScene.getLastChild().attachChild(shells);
                     break;
                  }
                 else if (arrAllObject.get(i).kindOfObject == Constant.FISH) {

                     int y = rand.nextInt(230) + 160;
                     int x = -1;
                     int fishKind = -1;
                     if (nLevel == 1) {
                         if (i < 6) {
                             fishKind = rand.nextInt(2);
                         } else {
                             fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH - 4);
                         }
                     }
                     else if (nLevel == 2) fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH - 3);
                     else if (nLevel == 3) fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH - 2);
                     else if (nLevel == 4) fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH -1);
                     else if (nLevel == 5) fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH);
                     sideAppear = rand.nextInt(2);
                     Fish fish = null;
                     if (sideAppear == Constant.LEFT) {
                         x = -20;
                         fish = new Fish(x, y, arrFishImgBack[fishKind], sideAppear, fishKind);
                     } else if (sideAppear == Constant.RIGHT) {
                         x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                         fish = new Fish(x, y, arrFishImg[fishKind], sideAppear, fishKind);
                     }
                     fish.animate(200);
                     arrAllObject.remove(i);
                     arrAllObject.add(i,(AbstractObject)fish);
                     myScene.getLastChild().attachChild(fish);
                     break;
                }
                else if (arrAllObject.get(i).kindOfObject == Constant.SHRIMP) {

                     int y = rand.nextInt(230) + 160;
                     int x = -1;
                     int shrimpKind = 0;
                     sideAppear = rand.nextInt(2);
                     Shrimp shrimp = null;
                     if (sideAppear == Constant.LEFT) {
                         x = -20;
                         shrimp = new Shrimp(x, y, arrShrimpImg[shrimpKind], sideAppear, shrimpKind);
                         shrimp.setRotation(90);
                     } else if (sideAppear == Constant.RIGHT) {
                         x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                         shrimp = new Shrimp(x, y, arrShrimpImgBack[shrimpKind], sideAppear, shrimpKind);
                         shrimp.setRotation(270);
                     }
                     shrimp.animate(500);
                     arrAllObject.remove(i);
                     arrAllObject.add(i,(AbstractObject)shrimp);
                     myScene.getLastChild().attachChild(shrimp);
                     break;
                }
                else if(arrAllObject.get(i).kindOfObject == Constant.ITEM){

                }
            }
        }
    }
    
    private void checkColitionAllObject(){

         iTimeToResetDirect++;
         if (iTimeToResetDirect == 10) {
             iTimeToResetDirect = 0;
             isReset  = false;
         }
         if (isReset) return;

         // duyen qua danh sach,check va cham cua 1 doi tuong voi nhung doi tuong khac
         for (int i = 0; i < arrAllObject.size(); i++) {
            if (arrAllObject.get(i) != null) {
                for (int j = i + 1; j < arrAllObject.size() - 1; j++) {
                    if (arrAllObject.get(j).collidesWith(arrAllObject.get(i))) {
                        // check xem co phai ca ko, neu dung thi co con nao an duoc nhau ko
                        if (nLevel > 3 && arrAllObject.get(i).kindOfObject == Constant.FISH && arrAllObject.get(j).kindOfObject == Constant.FISH) {
                            Fish fish = (Fish)arrAllObject.get(i);
                            Fish fish1 = (Fish)arrAllObject.get(j);
                            if (fish.kind == 6 || fish.kind == 7) {// ca hung du
                                if (fish1.kind == 0 || fish1.kind == 1 || fish1.kind == 2 || fish1.kind == 3 || fish1.kind == 4 || fish1.kind == 5) {// ca hien
                                    myScene.getLastChild().detachChild(arrAllObject.get(j));
                                    arrAllObject.remove(j);
                                    int y = rand.nextInt(230) + 160;
                                    int x = -1;
                                    int fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH - 2);
                                    sideAppear = rand.nextInt(2);
                                    Fish fish11 = null;
                                    if (sideAppear == Constant.LEFT) {
                                         x = -20;
                                         fish11 = new Fish(x, y, arrFishImgBack[fishKind], sideAppear, fishKind);
                                    } else if (sideAppear == Constant.RIGHT) {
                                         x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                                         fish11 = new Fish(x, y, arrFishImg[fishKind], sideAppear, fishKind);
                                    }
                                    fish11.animate(200);
                                    arrAllObject.add(j, (AbstractObject)fish11);
                                    myScene.getLastChild().attachChild(fish11);
                                    break;
                                }
                            }
                        } else if (arrAllObject.get(i).kindOfObject == Constant.MOSS || arrAllObject.get(i).kindOfObject == Constant.CRAB || arrAllObject.get(i).kindOfObject == Constant.SHELLS) {
                                  arrAllObject.get(j).resetDirection();
                        } else {
                                arrAllObject.get(i).resetDirection();
                                arrAllObject.get(j).resetDirection();
                        }
                    }
                }
            }
        }

        isReset= true;
    }

    int timefish = 0;
    private void paintLineFishing() {
        if (boat != null) {
            if (boat.isFishing) {
                float lineX = boat.getX()+Constant.LINEBOUNDX;
                float lineY = boat.getY()+Constant.LINEBOUNDY;
                float hookX = lineX - Constant.HOOKBOUNDX;

                if (lengthInTime <= boat.lengthsOfline && isPickUp) {
                    lengthInTime += boat.speed;
                    if (hook != null) {
                        myScene.getLastChild().detachChild(hook);
                    }
                    if (line!= null) {
                        myScene.getLastChild().detachChild(line);
                    }

                    line = new Line(lineX, lineY, lineX, lineY + lengthInTime);
                    line.setColor(0, 0, 0);
                    hook = new AnimatedSprite(lineX, lineY + lengthInTime, this.mfishingrodTextureRegion);
                    hook.setPosition( hookX, lineY + lengthInTime+ Constant.DISTANCEHOOK);

                    boolean check = checkFishingWithObject(hook);
                    if (!check) {
                        myScene.getLastChild().attachChild(hook);
                        myScene.getLastChild().attachChild(line);
                        isPickUp = true;
                    }
                    else if (check) {
                        isPickUp = false;
                        //play and stop beat sound
                        if(fishbeatSound.isPlaying())
                        {
                        	Utils.stopMediaPlayer(fishbeatSound);                        	
                        }
                        Utils.playMediaPlayer(fishbeatSound, false);
                    }
                }
                else
                {

                    isPickUp = false;
                    lengthInTime= (int)((lengthInTime > Constant.DISTANCELINE) ? lengthInTime - boat.speed : Constant.DISTANCELINE);
                    if (lengthInTime > Constant.DISTANCELINE) {
                        if (line != null) {
                            myScene.getLastChild().detachChild(line);
                        }
                        if (hook != null) {
                            myScene.getLastChild().detachChild(hook);
                        }
                        line = new Line(lineX, lineY, lineX, lineY + lengthInTime);
                        line.setColor(0, 0, 0);
                        hook = new AnimatedSprite(lineX, lineY + lengthInTime, this.mfishingrodTextureRegion);
                        hook.setPosition( hookX, lineY + lengthInTime+ Constant.DISTANCEHOOK);
                        myScene.getLastChild().attachChild(hook);
                        myScene.getLastChild().attachChild(line);

                    }
                    else {
                    	
                         if(TIMER >= timefish + 2) {
                        	 if (mFishText != null) {
                        		 myHud.getLastChild().detachChild(mFishText);
                        	 }
                             timefish = 0;
                         }
                         
                         if (line != null) {
                             myScene.getLastChild().detachChild(line);
                         }
                         
                         if (hook != null) {
                             myScene.getLastChild().detachChild(hook);
                         }
                         
                         moveLineFish();
                         
                         if (fishColie != null) {
                             myScene.getLastChild().detachChild(arrAllObject.get(indexFish));
                             arrAllObject.remove(indexFish);
                             AbstractObject obj = null;
                             fishColie = null;
                             int y = rand.nextInt(230) + 160;
                             int fishKind = 0;
                             if (nLevel == 1) {
                                     fishKind = rand.nextInt(2);
                             }
                             else if (nLevel == 2) fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH - 3);
                             else if (nLevel == 3) fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH - 2);
                             else if (nLevel == 4) fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH -1);
                             else if (nLevel == 5) fishKind = rand.nextInt(Constant.NUM_OF_KIND_FISH);
                             sideAppear = rand.nextInt(2);
                             if (sideAppear == Constant.LEFT) {
                                 int x =  -20;
                                 obj = new Fish(x, y, arrFishImgBack[fishKind], sideAppear, fishKind);
                             } else if (sideAppear == Constant.RIGHT) {
                                 int x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                                 obj = new Fish(x, y, arrFishImg[fishKind], sideAppear, fishKind);
                            }
                             obj.animate(200);
                             arrAllObject.add(indexFish, obj);
                             myScene.getLastChild().attachChild(obj);

                         }
                         if(shrimpColie != null) {
                             myScene.getLastChild().detachChild(arrAllObject.get(indexShrimp));
                             arrAllObject.remove(indexShrimp);
                             AbstractObject obj = null;
                             shrimpColie = null;
                             int y = rand.nextInt(230) + 160;
                             int shrimpKind = 0;
                             sideAppear = rand.nextInt(2);
                             if (sideAppear == Constant.LEFT) {
                                 int x =  -20;
                                 obj = new Shrimp(x, y, arrShrimpImg[shrimpKind], sideAppear, shrimpKind);
                                 obj.setRotation(90);
                             } else if (sideAppear == Constant.RIGHT) {
                                 int x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                                 obj = new Shrimp(x, y, arrShrimpImgBack[shrimpKind], sideAppear, shrimpKind);
                                 obj.setRotation(270);
                            }
                            obj.animate(500);
                            arrAllObject.add(indexShrimp, obj);
                            myScene.getLastChild().attachChild(obj);

                         }
                         if(crabColie != null) {
                             myScene.getLastChild().detachChild(arrAllObject.get(indexCrab));
                             arrAllObject.remove(indexCrab);
                             crabColie = null;
                             int y = 420;
                             int crabKind = 0;
                             int x = -1;
                             sideAppear = rand.nextInt(2);
                             if (sideAppear == Constant.LEFT) {
                                 x = -20;
                             } else if (sideAppear == Constant.RIGHT) {
                                 x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                            }
                            AbstractObject obj = new Crab(x, y, arrShrimpImg[crabKind], sideAppear, crabKind);
                            obj.animate(1000);
                            arrAllObject.add(indexCrab, obj);
                            myScene.getLastChild().attachChild(obj);

                         }
                         if(shellsColie != null) {
                             myScene.getLastChild().detachChild(arrAllObject.get(indexShells));
                             arrAllObject.remove(indexShells);
                             shellsColie = null;
                             int y = 450;
                             int shellsKind = 0;
                             int x = -1;
                             sideAppear = rand.nextInt(2);
                             if (sideAppear == Constant.LEFT) {
                                 x = -30;
                             } else if (sideAppear == Constant.RIGHT) {
                                 x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 30;
                            }
                            AbstractObject obj = new Shells(x, y, arrShrimpImg[shellsKind], sideAppear, shellsKind);
                            obj.animate(200);
                            arrAllObject.add(indexShells, obj);
                            myScene.getLastChild().attachChild(obj);

                         }
                         // cap nhat diem
                         mScoreText.setText("Score:" + iTotalScore);
                         boat.isFishing = false;
                    }
                }
            }
            boat.isMoving = false;
        }

    }
    
    private boolean checkFishingWithObject(AnimatedSprite fishingRod2) {
        boolean isCollision = false;
        int iTotalMoneyBefore = iTotalScore;
        for (int i = 0; i < arrAllObject.size(); i++) {
            if (arrAllObject.get(i) != null) {
                if (arrAllObject.get(i).collidesWith(fishingRod2)) {
                    if (arrAllObject.get(i).kindOfObject == Constant.FISH) {
                        Fish fish = (Fish)arrAllObject.get(i);
                        fishColie = fish;
                        if(fish.weight <= boat.strength)
                        {
                            if (fish.kind != 4 && (fish.direction == Constant.LEFT || fish.direction == Constant.LEFT_UP || fish.direction == Constant.LEFT_DOWN)) {
                                fish.setRotation(90);
                            } else if (fish.kind != 4 && (fish.direction == Constant.RIGHT || fish.direction == Constant.RIGHT_UP || fish.direction == Constant.RIGHT_DOWN)) {
                                fish.setRotation(-90);
                            }
                            fish.setPosition(hook.getX() - (fish.getBaseWidth() / 2), hook.getY() + (fish.getBaseHeight() / 2));
                            fish.direction = Constant.UP;
                            indexFish = i;
                            isCollision = true;
                            iTotalScore += Constant.arrayPrice[fish.kind];
                            boat.amountOfMoney += Constant.arrayPrice[fish.kind];
                            int x = (int)fish.getX();
                            if (x > 480) x -= 300;  
                            mFishText.setPosition(x, fish.getY());
                            mFishText.setText(String.valueOf(iTotalScore - iTotalMoneyBefore));
                            myHud.getLastChild().attachChild(mFishText);
                            timefish = TIMER;
                        }
                        else
                        {
                            fish.setPosition(hook.getX(), (hook.getY() - (fish.getBaseHeight() / 2) + (hook.getBaseHeight() / 2)));
                            fish.speedX=0;
                            fish.speedY=0;
                            isCollision = false;
                        }
                        break;
                    }
                    else if (arrAllObject.get(i).kindOfObject == Constant.SHRIMP) {
                        Shrimp shrimp = (Shrimp)arrAllObject.get(i);
                        shrimpColie = shrimp;
                        if(shrimp.weight <= boat.strength)
                        {
                            if (shrimp.direction ==Constant.LEFT || shrimp.direction == Constant.LEFT_UP || shrimp.direction == Constant.LEFT_DOWN)
                            {
                                shrimp.setRotation(-360);
                            } else if(shrimp.direction ==Constant.RIGHT || shrimp.direction ==Constant.RIGHT_UP || shrimp.direction ==Constant.RIGHT_DOWN) {
                                shrimp.setRotation(360);
                            }
                            shrimp.setPosition(hook.getX() - (shrimp.getBaseWidth() / 2), hook.getY() + (shrimp.getBaseHeight() / 2));
                            shrimp.direction = Constant.UP;
                            indexShrimp = i;
                            isCollision = true;
                            iTotalScore+= 20;
                            boat.amountOfMoney += 20;
                            int x = (int)shrimp.getX();
                            if (x > 480) x -= 300;
                            mFishText.setPosition(shrimp.getX(), shrimp.getY());
                            mFishText.setText(String.valueOf(iTotalScore - iTotalMoneyBefore));
                            myHud.getLastChild().attachChild(mFishText);
                            timefish = TIMER;
                        }
                        else
                        {
                            shrimp.setPosition(hook.getX(), (hook.getY() - (shrimp.getBaseHeight() / 2) + (hook.getBaseHeight( )/ 2)));
                            shrimp.speedX=0;
                            shrimp.speedY=0;
                            isCollision = false;
                        }
                        break;
                    }
                    else if (arrAllObject.get(i).kindOfObject == Constant.CRAB) {
                        Crab crab = (Crab)arrAllObject.get(i);
                        crabColie = crab;
                        if(crab.weight <= boat.strength)
                        {

                            crab.setRotation(90);
                            crab.setPosition(hook.getX() - (crab.getBaseWidth() / 2), hook.getY() + (crab.getBaseHeight() / 2));
                            crab.direction = Constant.UP;
                            indexCrab = i;
                            isCollision = true;
                            iTotalScore+= 100;
                            boat.amountOfMoney += 100;
                            int x = (int)crab.getX();
                            if (x > 480) x -= 300;
                            mFishText.setPosition(x, crab.getY());
                            mFishText.setText(String.valueOf(iTotalScore - iTotalMoneyBefore));
                            myHud.getLastChild().attachChild(mFishText);
                            timefish = TIMER;
                        }
                        else
                        {
                            crab.setPosition(hook.getX(), (hook.getY() - (crab.getBaseHeight() / 2) + (hook.getBaseHeight() / 2)));
                            crab.speedX=0;
                            crab.speedY=0;
                            isCollision = false;
                        }
                        break;
                    }
                    else if (arrAllObject.get(i).kindOfObject == Constant.SHELLS) {
                        Shells shells = (Shells)arrAllObject.get(i);
                        shellsColie = shells;
                        if(shells.weight <= boat.strength)
                        {
                            shells.setPosition(hook.getX() - (shells.getBaseWidth() / 2), hook.getY() + (shells.getBaseHeight() / 2));
                            shells.direction = Constant.UP;
                            indexShells = i;
                            isCollision = true;
                            iTotalScore+= 100;
                            boat.amountOfMoney += 100;
                            int x = (int)shells.getX();
                            if (x > 480) x -= 300;
                            mFishText.setPosition(x, shells.getY());
                            mFishText.setText(String.valueOf(iTotalScore - iTotalMoneyBefore));
                            myHud.getLastChild().attachChild(mFishText);
                            timefish = TIMER;
                        }
                        else
                        {
                            shells.setPosition(hook.getX(), (hook.getY() - (shells.getBaseHeight() / 2) + (hook.getBaseHeight() / 2)));
                            shells.speedX=0;
                            shells.speedY=0;
                            isCollision = false;
                        }
                        break;
                    }
                    else if (arrAllObject.get(i).kindOfObject == Constant.MOSS) {
                        isPickUp = false;
                        isCollision = true;
                        break;
                    }

                }
            }
        }
        return isCollision;
    }
    
    @Override
    public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
    	
        if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) {

            if (pauseMenu == null) {
                pauseMenu = new PauseMenuDialog(this);
            }
            pauseMenu.show();
            return true;

        } else {
            return super.onKeyDown(pKeyCode, pEvent);
        }
    }
    
	@Override
	public void onBackPressed() {
        if (this.mEngine.isRunning()) {
        	this.mEngine.stop();
	    } else {
	        this.mEngine.start();
	    }
        finish();
        Intent intent = new Intent(GameActivity.this, MenuActivity.class);
        startActivity(intent);
	}
    
    /**
     * get width of timer bar
     * @return width
     */
    public float getWidthOfTimerBar() {
        if (percentTimeBar <= 0) {
            percentTimeBar = 0;
        }
        return percentTimeBar*(WIDTH_OF_TIMER_BAR / 100);
    }
    
    boolean isCheat = true;
    //quan ly tat ca cac vung touch
    @Override
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent, ITouchArea pTouchArea, float pTouchAreaLocalX, float pTouchAreaLocalY)
    {
        boolean isMove = false;
        boolean isDown = false;

        if (lengthInTime > Constant.DISTANCELINE || !this.mGameRunning) return false;
            
        if (pSceneTouchEvent.isActionMove()) {
            if(pTouchArea.equals(iconcau)) //kiem tra doi tuong touch co phai la icon cau khong
            {
                boat.isFishing = false;
                isMove = true;
                isDown = false;
            }
        }
        if (pSceneTouchEvent.isActionDown()) {
            if (pTouchArea.equals(iconcau)) //kiem tra doi tuong touch co phai la icon cau khong
            {
                if (lengthInTime == Constant.DISTANCELINE)
                {
                  isDown = true;
                  isMove = false;
                }
            } else if (pTouchArea.equals(cheat)) {
                if (isCheat)
                    if (nLevel == 1) {
                        iTotalScore = 40;
                        boat.amountOfMoney = 40;
                    } else if (nLevel == 2) {
                        iTotalScore = 80;
                        boat.amountOfMoney = 80;
                    } else if (nLevel == 3) {
                        iTotalScore = 150;
                        boat.amountOfMoney = 150;
                    } else if (nLevel == 4) {
                        iTotalScore = 300;
                        boat.amountOfMoney = 300;
                    } else if (nLevel == 5) {
                        iTotalScore = 500;
                        boat.amountOfMoney = 500;
                    }
                    percentTimeBar = 0;
                    isCheat = false;
            }
        }
        if (isDown && !isMove) {
            if (pTouchArea.equals(iconcau)) //kiem tra doi tuong touch co phai la icon cau khong
            {
                if (lengthInTime == Constant.DISTANCELINE)
                {
                    isPickUp = true;
                    boat.isFishing = true;
                }
                isDown = false;
                isMove = false;
            }
        }
        return true;
    }

    private void loadGame() {
    	
        if (gameModel == null) {
            gameModel = new GameModel(getApplicationContext());
        }
        ArrayList<MainGame>  listG = gameModel.getDataList();
        if (listG.size() >= 1) {
            nLevel = listG.get(0).getLevel();
            iTotalScore = listG.get(0).getScore();
            percentTimeBar = listG.get(0).getTimePercent();
        }
        iTimerInLevel = Constant.arrayTimeInLevels[nLevel-1];
        this.mScoreText.setText("Score:"+iTotalScore);
        this.mLevelText.setText("Level:" + nLevel);
        this.mGoalText.setText("Target:" + Constant.arrayMoneyInLevels[nLevel-1]);

        if (animalModel == null) {
            animalModel = new AnimalModel(getApplicationContext());
        }
        ArrayList<AnimalToRestore>  list = animalModel.getDataList();

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != null) {
                if (list.get(i).getKindAnimal() == Constant.FISH) {
                    int ikind = list.get(i).getsubkindAnimal();
                    Fish fish = null;
                    if (ikind == Constant.RIGHT || ikind == Constant.RIGHT_DOWN || ikind == Constant.RIGHT_UP) {
                        fish = new Fish(list.get(i).getX(), list.get(i).getY(), arrFishImg[ikind],
                                ikind, list.get(i).getVx(), list.get(i).getVy(), list.get(i).getDirection(),
                                list.get(i).getWeight(), list.get(i).getTimeToResetDirect(), SetReset(list.get(i).getIsReset()));
                    } else if (ikind == Constant.LEFT || ikind == Constant.LEFT_DOWN || ikind == Constant.LEFT_UP) {
                        fish = new Fish(list.get(i).getX(), list.get(i).getY(), arrFishImgBack[ikind], ikind, list.get(i).getVx(),
                                list.get(i).getVy(), list.get(i).getDirection(), list.get(i).getWeight(), list.get(i).getTimeToResetDirect(), SetReset(list.get(i).getIsReset()));
                    }
                    arrAllObject.add(fish);
                }
                else if (list.get(i).getKindAnimal() == Constant.MOSS) {
                    int ikind = list.get(i).getsubkindAnimal();
                    Moss moss = new Moss(list.get(i).getX(), list.get(i).getY(),mossTextureRegion, ikind, list.get(i).getVx(), list.get(i).getVy(), list.get(i).getDirection(), list.get(i).getWeight(), list.get(i).getTimeToResetDirect(), SetReset(list.get(i).getIsReset()));
                    arrAllObject.add(moss);

                }
                else if (list.get(i).getKindAnimal() == Constant.CRAB) {
                     int ikind = list.get(i).getsubkindAnimal();
                     Crab crab = new Crab(list.get(i).getX(), list.get(i).getY(), crabTextureRegion, ikind, list.get(i).getVx(), list.get(i).getVy(), list.get(i).getDirection(), list.get(i).getWeight(), list.get(i).getTimeToResetDirect(), SetReset(list.get(i).getIsReset()));
                     arrAllObject.add(crab);
                }
                else if (list.get(i).getKindAnimal() == Constant.SHELLS) {
                    int ikind = list.get(i).getsubkindAnimal();
                    Shells shells = new Shells(list.get(i).getX(), list.get(i).getY(), crabTextureRegion, ikind, list.get(i).getVx(), list.get(i).getVy(), list.get(i).getDirection(), list.get(i).getWeight(), list.get(i).getTimeToResetDirect(), SetReset(list.get(i).getIsReset()));
                    arrAllObject.add(shells);
               }
                else if (list.get(i).getKindAnimal() == Constant.SHRIMP) {
                     int ikind = list.get(i).getsubkindAnimal();
                     Shrimp shrimp = null;
                     if(ikind == Constant.RIGHT || ikind == Constant.RIGHT_DOWN || ikind == Constant.RIGHT_UP) {
                    	 shrimp =  new Shrimp(list.get(i).getX(), list.get(i).getY(), arrShrimpImgBack[ikind], ikind, list.get(i).getVx(), list.get(i).getVy(), list.get(i).getDirection(), list.get(i).getWeight(), list.get(i).getTimeToResetDirect(), SetReset(list.get(i).getIsReset()));
                         shrimp.setRotation(90);
                     } else if (ikind == Constant.LEFT || ikind == Constant.LEFT_DOWN || ikind == Constant.LEFT_UP) {
                    	 shrimp =  new Shrimp(list.get(i).getX(), list.get(i).getY(), arrShrimpImg[ikind], ikind, list.get(i).getVx(), list.get(i).getVy(), list.get(i).getDirection(), list.get(i).getWeight(), list.get(i).getTimeToResetDirect(), SetReset(list.get(i).getIsReset()));
                    	 shrimp.setRotation(270);
                     }
                     arrAllObject.add(shrimp);
                }
            }
        }
        if (personModel == null) {
            personModel = new PersonModel(getApplicationContext());
        }
        ArrayList<PersonToRestore>  listP = personModel.getDataList();
        boat = new Person(listP.get(0).getXposition(),listP.get(0).getYposition(), boatTextureRegion, listP.get(0).getDirection(), listP.get(0).getSideAppear(),listP.get(0).getBlood(), listP.get(0).getStrength(), listP.get(0).getLengthsOfline(), listP.get(0).getAmoutnOFMoney());//, personlist.isMoving(), personlist.isTimeDelayInFishing());
        for (int i = 0; i < arrAllObject.size(); i++) {
            myScene.getLastChild().attachChild(arrAllObject.get(i));
        }
        myScene.getLastChild().attachChild(boat);
    }
    
    public boolean SetReset(int in) {
        if (in == 1) {
            return  true;
        } else {
            return false;
        }
    }

    private void saveGame() {
        // luu thong tin cac object trong game
        if (animalModel == null) {
            animalModel = new AnimalModel(getApplicationContext());
        }
        animalModel.deleteAll();
        if (arrAllObject == null) {
            arrAllObject = new ArrayList<AbstractObject>();
        }
        for (int i = 0; i < arrAllObject.size(); i++) {
            if (arrAllObject.get(i) != null) {
                if (arrAllObject.get(i).kindOfObject == Constant.FISH) {
                    Fish fish = (Fish)arrAllObject.get(i);
                    animalModel.Insert(Constant.FISH, fish.kind, (int)fish.getX(),(int)fish.getY(), fish.direction, fish.weight, fish.iTimeToResetDirect, fish.converResetToInt(), (int)fish.speedX, (int)fish.speedY);
                } else if (arrAllObject.get(i).kindOfObject == Constant.CRAB) {
                    Crab crab = (Crab)arrAllObject.get(i);
                    animalModel.Insert(Constant.CRAB, 0, (int)crab.getX(),(int)crab.getY(),  crab.direction, crab.weight, crab.iTimeToResetDirect, crab.converResetToInt(),(int)crab.speedX, (int)crab.speedY);
                } else if (arrAllObject.get(i).kindOfObject == Constant.SHRIMP) {
                    Shrimp shrimp = (Shrimp)arrAllObject.get(i);
                    animalModel.Insert(Constant.SHRIMP, 0, (int)shrimp.getX(),(int)shrimp.getY(),  shrimp.direction, shrimp.weight, shrimp.iTimeToResetDirect, shrimp.converResetToInt(),(int)shrimp.speedX, (int)shrimp.speedY);
                } else if (arrAllObject.get(i).kindOfObject == Constant.MOSS) {
                    Moss moss = (Moss)arrAllObject.get(i);
                    animalModel.Insert(Constant.MOSS, moss.kind, (int)moss.getX(),(int)moss.getY(), moss.direction, moss.weight, moss.iTimeToResetDirect, moss.converResetToInt(),(int)moss.speedX, (int)moss.speedY);
	            } else if (arrAllObject.get(i).kindOfObject == Constant.SHELLS) {
	                Shells shells = (Shells)arrAllObject.get(i);
	                animalModel.Insert(Constant.SHELLS, shells.kind, (int)shells.getX(),(int)shells.getY(), shells.direction, shells.weight, shells.iTimeToResetDirect, shells.converResetToInt(),(int)shells.speedX, (int)shells.speedY);
	            }
            }
        }
        // luu thong tin nguoi choi

        if (personModel == null) {
            personModel = new PersonModel(getApplicationContext());
        }
        personModel.deleteAll();
        personModel.Insert((int)boat.xFishing,(int)boat.yFishing,boat.direction, (int)boat.sideAppear,(int)boat.blood, (int)boat.strength, (int)boat.lengthsOfline, (int)boat.amountOfMoney,boat.convertToInt(boat.isCatchOk),boat.convertToInt(boat.isMoving),boat.convertToInt(boat.isTimeDelayInFishing),(int)(boat.getX()+boat.getWidth()),(int)boat.getY());//, (boolean)boat.isMoving, (boolean)boat.isTimeDelayInFishing);
        // luu thong tin game
        if (gameModel == null) {
            gameModel = new GameModel(getApplicationContext());
        }
        gameModel.deleteAll();
        gameModel.Insert(nLevel, iTotalScore, percentTimeBar);
    }

    private void initGameText()
    {
         /* The game-over text. */
        if (this.mGameOverText == null) {
            this.mGameOverText = new ChangeableText(0, 0, this.mFont, "Game\nOver", "Game\nOver".length());
        }
        this.mGameOverText.setPosition((MenuActivity.CAMERA_WIDTH - this.mGameOverText.getWidth()) * 0.5f, (MenuActivity.CAMERA_HEIGHT - this.mGameOverText.getHeight()) * 0.5f);
        this.mGameOverText.registerEntityModifier(new ScaleModifier(3, 0.1f, 2.0f));
        this.mGameOverText.registerEntityModifier(new RotationModifier(3, 0, 720));

        /* The congratulations text. */
        if (this.mCongratulationsText == null) {
        	this.mCongratulationsText = new ChangeableText(0, 0, this.mFont, "Congratulations\n    You won!", "Congratulations\n    You won!".length());
        }
        this.mCongratulationsText.setPosition((MenuActivity.CAMERA_WIDTH - this.mCongratulationsText.getWidth()) * 0.5f, (MenuActivity.CAMERA_HEIGHT - this.mCongratulationsText.getHeight()) * 0.5f);
        this.mCongratulationsText.registerEntityModifier(new ScaleModifier(3, 0.1f, 2.0f));
        this.mCongratulationsText.registerEntityModifier(new RotationModifier(3, 0, 720));

        /* The level text. */
        if (this.mLevelText == null) {
            this.mLevelText = new ChangeableText(MenuActivity.CAMERA_WIDTH - 550, 5, this.mFont, "Level:" + nLevel, "Level:X".length());
        }
        this.mLevelText.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        this.mLevelText.setAlpha(0.5f);
        this.mLevelText.setColor(0, 1, 1);
        myHud.getLastChild().attachChild(mLevelText);

        /* The goal text. */
        if (this.mGoalText == null) {
            this.mGoalText = new ChangeableText(MenuActivity.CAMERA_WIDTH - 300, 35, this.mFont, "Target:" + Constant.arrayMoneyInLevels[nLevel-1], "Target:XXXX".length());
        }
        this.mGoalText.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        this.mGoalText.setAlpha(0.5f);
        this.mGoalText.setColor(0, 1, 1);
        myHud.getLastChild().attachChild(mGoalText);

        /* The animal score text. */
        if (this.mFishText == null) {
          this.mFishText = new ChangeableText(0, 0, this.mFont, "XX", "XX".length());
        }
        this.mFishText.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        this.mFishText.setAlpha(0.5f);
        this.mFishText.setColor(0, 0, 1);

        /*The score text*/
        if (this.mScoreText == null) {
            this.mScoreText = new ChangeableText(MenuActivity.CAMERA_WIDTH - 300, 5, this.mFont, "Score:0", "Score:XXXX".length());
        }
        this.mScoreText.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        this.mScoreText.setAlpha(0.5f);
        this.mScoreText.setColor(0, 1, 1);
        myHud.getLastChild().attachChild(mScoreText);
    }

    private void initilize(int level) {

        int num_of_kind_fish = 0;
        int num_of_fish = 0;
        boolean isCrab = false;
        boolean isShrimp = false;
        boolean isMoss = false;
        boolean isShells = false;
        iTimerInLevel = Constant.arrayTimeInLevels[nLevel-1];
        this.mScoreText.setText("Score:"+iTotalScore);
        this.mLevelText.setText("Level:" + nLevel);
        this.mGoalText.setText("Target:" + Constant.arrayMoneyInLevels[nLevel-1]);
        percentTimeBar = 100;
        fishColie = null;
        shrimpColie = null;
        crabColie = null;
        shellsColie = null;
        
        myScene.getLastChild().detachChild(line);
        myScene.getLastChild().detachChild(hook);
     
        if(boat == null) {
            boat = new Person(0, Constant.BOATBOUNDY - boatTextureRegion.getHeight() , boatTextureRegion, 0);
        } else {
        	boat.setPosition(0, Constant.BOATBOUNDY - boatTextureRegion.getHeight());
        }
        myScene.getLastChild().attachChild(boat);

        hook = new AnimatedSprite(boat.getX() + Constant.LINEBOUNDX - Constant.HOOKBOUNDX, boat.getY() + Constant.LINEBOUNDY + Constant.DISTANCEHOOK, this.mfishingrodTextureRegion);
        line = new Line(boat.getX() + Constant.LINEBOUNDX, boat.getY() + Constant.LINEBOUNDY, boat.getX()+Constant.LINEBOUNDX, boat.getY() + Constant.LINEBOUNDY);

        myScene.getLastChild().attachChild(line);
        myScene.getLastChild().attachChild(hook);
        
        if (level == 1)
        {
            num_of_kind_fish = Constant.NUM_OF_KIND_FISH - 4;
            num_of_fish = Constant.NUM_OF_FISH - 3;
            try {
 
            	this.mTMXTiledMap = tmxLoader.loadFromAsset(this, "tmx/bg1.tmx");

            } catch (final TMXLoadException tmxle) {
                Debug.e(tmxle);
            }
            TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
            myScene.getFirstChild().attachChild(tmxLayer);
            
        } else if (level == 2) {
            num_of_kind_fish = Constant.NUM_OF_KIND_FISH - 3;
            num_of_fish = Constant.NUM_OF_FISH - 2;
            isShrimp = true;
            isMoss = true;

        } else if (level == 3) {
            num_of_kind_fish = Constant.NUM_OF_KIND_FISH - 2;
            num_of_fish = Constant.NUM_OF_FISH - 1;
            isShrimp = true;
            isMoss = true;
            isShells = true;

        } else if (level == 4) {
            num_of_kind_fish = Constant.NUM_OF_KIND_FISH - 1;
            num_of_fish = Constant.NUM_OF_FISH - 1;
            isShrimp = true;
            isMoss = true;
            try {

            	this.mTMXTiledMap = tmxLoader.loadFromAsset(this, "tmx/bg2.tmx");

            } catch (final TMXLoadException tmxle) {
                Debug.e(tmxle);
            }
            TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
            myScene.getFirstChild().attachChild(tmxLayer);

        } else if (level == 5) {
            num_of_kind_fish = Constant.NUM_OF_KIND_FISH;
            num_of_fish = Constant.NUM_OF_FISH;
            isShrimp = true;
            isMoss = true;
            isCrab = true;
            isShells = true;
        }
        // oc
        if (isShells)
        for (int i = 0; i < Constant.NUM_OF_SHELLS; i++) {

            int y = 450;
            int x = -1;
            int shellsKind = 0;
            sideAppear = rand.nextInt(2);
            if (sideAppear == Constant.LEFT) {
                 x = -30;
            }
            else if (sideAppear == Constant.RIGHT) {
                x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 30;
            }
            Shells shells = new Shells(x, y, shellsTextureRegion, sideAppear, shellsKind);
            shells.animate(100);
            arrAllObject.add((AbstractObject)shells);
         }
        //item
        //cua
        if (isCrab)
        for (int i = 0; i < Constant.NUM_OF_CRAB; i++) {

            int y = 420;
            int x = -1;
            int crabKind = 0;
            sideAppear = rand.nextInt(2);
            if (sideAppear == Constant.LEFT) {
                 x = -20;
            }
            else if (sideAppear == Constant.RIGHT) {
                x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
            }
            Crab crab = new Crab(x, y, crabTextureRegion, sideAppear, crabKind);
            crab.animate(1000);
            arrAllObject.add((AbstractObject)crab);
         }
         //tom
         if (isShrimp)
         for (int i = 0; i < Constant.NUM_OF_SHRIMP; i++) {
            int y = rand.nextInt(230) + 160;
            int x = -1;
            int shrimpKind = 0;
            sideAppear = rand.nextInt(2);
            Shrimp shrimp = null;
            if (sideAppear == Constant.LEFT) {
                x = -20;
                shrimp = new Shrimp(x, y, arrShrimpImg[shrimpKind], sideAppear, shrimpKind);
                shrimp.setRotation(90);
           } else if (sideAppear == Constant.RIGHT) {
                x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                shrimp = new Shrimp(x, y, arrShrimpImgBack[shrimpKind], sideAppear, shrimpKind);
                shrimp.setRotation(270);
           }
           shrimp.animate(500);
           arrAllObject.add((AbstractObject)shrimp);
         }

        //rong
        if (isMoss)
        for (int i = 0; i < Constant.NUM_OF_MOSS; i++) {

            int y = rand.nextInt(100) + 160;
            int x = -1;
            int mossKind = 1;
            sideAppear = rand.nextInt(2);
            if (sideAppear == Constant.LEFT) {
                 x = -20;
            }
            else if (sideAppear == Constant.RIGHT) {
                x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
            }
            Moss moss = new Moss(x, y, mossTextureRegion, sideAppear, mossKind);
            moss.animate(1000);
            arrAllObject.add((AbstractObject)moss);
        }

        for (int i = 0; i < num_of_fish; i++) {
             int y = rand.nextInt(230) + 160;// tao so ngau nhien tu 250--->480
             int x = -1;
             int fishKind = -1;
             if (nLevel == 1 && i < 6) {
                 fishKind = rand.nextInt(2);
             } else {
                 fishKind = rand.nextInt(num_of_kind_fish);
             }
             sideAppear = rand.nextInt(2);
             Fish fish = null;
             if (sideAppear == Constant.LEFT) {
                 x = -20;
                 fish = new Fish(x, y, arrFishImgBack[fishKind], sideAppear, fishKind);
             } else if (sideAppear == Constant.RIGHT) {
                 x = MenuActivity.CAMERA_WIDTH + MenuActivity.CAMERA_WIDTH / 2 + 20;
                 fish = new Fish(x, y, arrFishImg[fishKind], sideAppear, fishKind);
             }
             arrAllObject.add((AbstractObject)fish);
             fish.animate(200);
        }

        // duyet qua danh sach cac doi tuong,cho vao scenne
        for (int i = 0; i < arrAllObject.size(); i++) {
            myScene.getLastChild().attachChild(arrAllObject.get(i));
        }
        this.mGameRunning = true;
    }

    public void onGameOver() {

        mGameOverText.setPosition((MenuActivity.CAMERA_WIDTH - this.mGameOverText.getWidth()) * 0.5f, (MenuActivity.CAMERA_HEIGHT - this.mGameOverText.getHeight()) * 0.5f);
        mGameOverText.setText("Game\nOver");
        this.mGameRunning = false;
        stopAllSounds();
        clearAnimation();
        isOverGameorCongras = 1;
    }

    public void onCompleted() {
    	mCongratulationsText.setPosition((MenuActivity.CAMERA_WIDTH - (this.mCongratulationsText.getWidth())) * 0.5f, (MenuActivity.CAMERA_HEIGHT - this.mCongratulationsText.getHeight()) * 0.5f);

    	mCongratulationsText.setText("CONGRATULATIONS\n    YOU WON!");
    	this.mGameRunning = false;
    	stopAllSounds();
    	clearAnimation();
    	isOverGameorCongras = 2;
    }

    int amountOfMoney = -1;
    private void increaseLevel() {

        mGameRunning = false;
        clearAnimation();
        if (nLevel < 5) {
             nLevel ++;
             amountOfMoney = boat.amountOfMoney;
             runOnUiThread(new Runnable() {
                 public void run() {
                	 if (nextLevel == null) {
                		 nextLevel = new NextLevelDialog(GameActivity.this, boat);
                     }
                     nextLevel.tVwLevel.setText("LEVEL " + String.valueOf(nLevel - 1) + " IS COMPLETED");
                     nextLevel.show();
                 }
             });
        }
        else
        {
            overTime ++;
            onCompleted();
            if(overTime == 5) {
                runOnUiThread(new Runnable() {
                    public void run() {
                       if (endGame == null) {
                           endGame = new EndGameDialog(GameActivity.this);
                       }
                       endGame.tVwLevel.setText("THE GAME IS COMPLETED");
                       endGame.show();
                    }
                });
                overTime = 0;
            }
        }
    }

    int overTime = 0;
    private void updateBarTimer() {

        if (TIMER % (6 * iTimerInLevel) == 0) {
            percentTimeBar--;
        }

        if (isTryAgain) {
            for (int i = 0; i< arrAllObject.size(); i++) {
                if (arrAllObject.get(i) != null) {
                    myScene.getLastChild().detachChild(arrAllObject.get(i));
                }
            }
            arrAllObject.clear();
            if (isOverGameorCongras == 2) {
                nLevel = 1;
                boat.amountOfMoney = 0;
                boat.strength = 5;
                boat.lengthsOfline = 200;
            } else if (isOverGameorCongras == 1) {
                boat.amountOfMoney = amountOfMoney;
            }
            isOverGameorCongras = 0;
            
            myHud.getLastChild().detachChild(mGameOverText);
            myHud.getLastChild().detachChild(mCongratulationsText);
            isIncreaseLevel = false;
            iTotalScore = 0;
            mGameRunning = true;
            isCheat = true;
            initilize(nLevel);
            isTryAgain = false;

        }
        
        if (isIncreaseLevel) {
            for (int i = 0; i < arrAllObject.size(); i++) {
                if (arrAllObject.get(i) != null) {
                    myScene.getLastChild().detachChild(arrAllObject.get(i));
                }
            }
            arrAllObject.clear();
            
 //           iTimerInLevel = 0;
            iTotalScore = 0;
            isCheat = true;
            initilize(nLevel);
            isIncreaseLevel = false;
        }

        if (percentTimeBar < 0) {

            if (iTotalScore < Constant.arrayMoneyInLevels[nLevel-1]) {
                overTime ++;
                onGameOver();
                if (overTime == 5) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                           if (endGame == null) {
                               endGame = new EndGameDialog(GameActivity.this);
                           }
                           myHud.getLastChild().detachChild(mGameOverText);
                           endGame.tVwLevel.setText("THE GAME IS NOT COMPLETED");
                           endGame.show();
                        }
                    });
                    overTime = 0;
                }
            } else if (iTotalScore >= Constant.arrayMoneyInLevels[nLevel-1]) {
                if (fishColie == null /*&& TIMER % 25 == 0*/ ) {
                    isIncreaseLevel = false;
                    increaseLevel();
                }

            }
        }
    }

    private void clearAnimation()  {
        for (int i = 0; i < arrAllObject.size(); i++) {
            if (arrAllObject.get(i) != null) {
                arrAllObject.get(i).stopAnimation();
            }
        }
    }

    private void startAnimation()
    {
        for (int i = 0; i< arrAllObject.size(); i++) {
            if (arrAllObject.get(i) != null) {
                if(arrAllObject.get(i).kindOfObject == Constant.FISH)
                    arrAllObject.get(i).animate(200);
                else if(arrAllObject.get(i).kindOfObject == Constant.SHRIMP)
                    arrAllObject.get(i).animate(500);
                else
                    arrAllObject.get(i).animate(1000);
            }
        }
    }

    @Override
    public void onGameResumed() {

        isSaveGame = settings.getBoolean("saveGamemode", false);
        if(isSaveGame){
            settings.edit().putBoolean("saveGamemode", false);
            settings.edit().commit();
            saveGame();
        }
          mGameRunning = true;
          startAnimation();
          //play sound
          if(!bgSound.isPlaying())
        	  Utils.playMediaPlayer(bgSound,false);
    }

    @Override
    public void onGamePaused() {

//		mGameRunning = false;
//		clearAnimation();
        //stop all sounds
        if(bgSound.isPlaying())
        	stopAllSounds();
    }
    private void moveLineFish()
    {

        float lineX = boat.getX()+Constant.LINEBOUNDX;
        float lineY = boat.getY()+Constant.LINEBOUNDY;
        float hookX = lineX - Constant.HOOKBOUNDX;
        if(line!=null)
            myScene.getLastChild().detachChild(line);
        if(hook!=null)
            myScene.getLastChild().detachChild(hook);
        line = new Line(lineX, lineY, lineX, lineY + lengthInTime);
        line.setColor(0, 0, 0);
        hook = new AnimatedSprite(lineX, lineY + lengthInTime, this.mfishingrodTextureRegion);
        hook.setPosition( hookX, (lineY + lengthInTime) + Constant.DISTANCEHOOK);
        myScene.getLastChild().attachChild(hook);
        myScene.getLastChild().attachChild(line);
    }
    
    private void stopAllSounds()
    {
    	Utils.stopMediaPlayer(bgSound);
        Utils.stopMediaPlayer(fishbeatSound);
    }

}
